package br.com.gkarian.mydesk.intercepts;

import br.com.caelum.vraptor.InterceptionException;
import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.core.InterceptorStack;
import br.com.caelum.vraptor.interceptor.Interceptor;
import br.com.caelum.vraptor.ioc.RequestScoped;
import br.com.caelum.vraptor.resource.ResourceMethod;
import br.com.gkarian.mydesk.anotacoes.RestritoAdmin;
import br.com.gkarian.mydesk.anotacoes.RestritoUsuario;
import br.com.gkarian.mydesk.controller.MainController;
import br.com.gkarian.mydesk.web.UsuarioWeb;

@RequestScoped
@Intercepts
public class AutenticacaoInterceptor implements Interceptor {

	private static final Integer AUTENTICACAO_ADMIN = 7;
	private final UsuarioWeb usuario;
	private final Result result;

	public AutenticacaoInterceptor(UsuarioWeb usuario, Result result) {
		this.usuario = usuario;
		this.result = result;
	}

	@Override
	public boolean accepts(ResourceMethod method) {
		if (method.getResource().getType().isAnnotationPresent(RestritoAdmin.class)
				|| method.getResource().getType().isAnnotationPresent(RestritoUsuario.class)
				|| method.containsAnnotation(RestritoUsuario.class)
				|| method.containsAnnotation(RestritoAdmin.class)) {
			if (usuario.isLogado()) {
				if (usuario.getAuth() == AUTENTICACAO_ADMIN) {
					return false;
				}
				if (method.containsAnnotation(RestritoUsuario.class)
						|| method.getResource().getType().isAnnotationPresent(RestritoUsuario.class)) {
					return false;
				}
				return true;
			}
			return true;
		} else {
			return false;
		}
	}

	// se accepts for TRUE, o metodo intercept eh executado
	public void intercept(InterceptorStack stack, ResourceMethod method,
			Object resourceInstance) throws InterceptionException {
		result.redirectTo(MainController.class).index();
	}
}